package com.itheima.aop;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class OperationLogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.itheima.aop.LogOperation)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Long start = System.currentTimeMillis();
        log.info("记录操作日志开始");
        //要保存的操作日志对象
        OperateLog operateLog = new OperateLog();
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setOperateEmpId(CurrentHolder.getCurrentId());
        String className = joinPoint.getTarget().getClass().getName();  //获取目标类名
        operateLog.setClassName(className);
        String methodName = joinPoint.getSignature().getName();   //获取目标方法名
        operateLog.setMethodName(methodName);
        Object[] args = joinPoint.getArgs();  //获取目标方法运行参数
        operateLog.setMethodParams(Arrays.toString(args));
        Object result = null;
        try {
            result = joinPoint.proceed();
            operateLog.setReturnValue(result.toString());
        } finally {
            operateLog.setCostTime(System.currentTimeMillis() - start);
            operateLogMapper.insert(operateLog);
        }
        log.info("记录操作日志结束");
        return result;
    }
}
